import type { Context } from 'koa'
import {
  selectAllWallpaper,
  addWallpaper,
  deleteWallpaper,
} from '../service/wallpaper.service.ts'
import { __dirname } from '../utils/common.ts'
import fs from 'fs'
import path from 'path'
const { APP_PORT, APP_HOST } = process.env
import { WallpaperGetUrlError } from '../constant/err.type.ts'
import { ensureDirectoryExists } from '../utils/fs.ts'

class WallpaperController {
  // 获取随机图片 http 地址
  async getRanImg(ctx: Context) {
    try {
      const israndom = ctx.request.query.israndom as string
      let imgUrl: string = ''
      const Path: string = path.join(__dirname(), '../upload/wallpaper')
      // 确保上传目录存在
      ensureDirectoryExists(Path)
      // 本地所有图片的名称集合
      let imgnameLocalArr: string[] = await fs.promises.readdir(Path)
      // 获取随机图片的信息
      const getRanImgName = async (list: string[]) => {
        return new Promise(resolve => {
          let imgname: string = ''
          if (list && list.length > 0) {
            // 随机索引
            const index: number = Math.floor(Math.random() * list.length)
            imgname = list[index]
            // 获取文件信息
            fs.stat(Path + '/' + imgname, (err, stats) => {
              if (err) throw err
              const size = (Number(stats.size) / 1024).toFixed(2)
              resolve({ imgname, size })
            })
          } else {
            resolve({ imgname, size: 0 })
          }
        })
      }
      if (imgnameLocalArr && imgnameLocalArr.length > 0) {
        let imgFileInfo: any
        // 不重复
        if (israndom === '1') {
          // 已随机过的图片信息集合
          let imgnameDatabase = await selectAllWallpaper()
          if (imgnameDatabase && imgnameDatabase.length > 0) {
            // 已随机过的图片名称集合
            imgnameDatabase = imgnameDatabase.map((item: any) => item.imgname)
            // 判断是否已经随机过所有图片
            const isExist = imgnameLocalArr.every(item =>
              imgnameDatabase.includes(item),
            )
            if (isExist) {
              // 随机过所有图片，删除所有记录
              await deleteWallpaper()
              // 重新随机
              imgFileInfo = await getRanImgName(imgnameLocalArr)
            } else {
              // 过滤掉已经随机过的图片，得到未随机过的图片
              let list = imgnameLocalArr.filter(
                item => !imgnameDatabase.includes(item),
              )
              // 在未随机过的图片中随机
              imgFileInfo = await getRanImgName(list)
            }
          } else {
            imgFileInfo = await getRanImgName(imgnameLocalArr)
          }
          await addWallpaper(imgFileInfo.imgname, imgFileInfo.size)
        }
        // 可重复
        else {
          imgFileInfo = await getRanImgName(imgnameLocalArr)
        }
        imgUrl = `http://${APP_HOST}:${APP_PORT}/wallpaper/${imgFileInfo.imgname}`
      }
      ctx.echo({ imgUrl })
    } catch (error) {
      WallpaperGetUrlError.error = error
      return ctx.app.emit('error', WallpaperGetUrlError, ctx)
    }
  }
}

const wallpaperController = new WallpaperController()
export const { getRanImg } = wallpaperController
export default wallpaperController
